/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Channel.Util.js
 * @path:   js-src/Channel/
 * @desc:
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
qui(function(require, exports, module) {

    Channel.Util = $.extend(true, {}, Ancestor.Util, {

        // jqGrid formater relative method 
        formatter: {
            qipuId: function(v, r) {
                if (dev)
                    return '<a href="http://qipu-test.qiyi.domain/int/entity/nocache/' + r.qipuId + '.json" target="_blank">' + r.qipuId + '</a>';//<br />老奇谱ID:<a href="http://qipu-test.qiyi.domain/int/entity/nocache/' + r.oldQipuId + '.json" target="_blank">' + r.oldQipuId + '</a>';
                else
                    return '<a href="http://qipu.qiyi.domain/int/entity/nocache/' + r.qipuId + '.json" target="_blank">' + r.qipuId + '</a>';//<br />老奇谱ID:<a href="http://qipu.qiyi.domain/int/entity/nocache/' + r.oldQipuId + '.json" target="_blank">' + r.oldQipuId + '</a>';
            },

            name: function(v, r) {

                return '<div style="word-wrap : break-word;word-break:break-all;"><a href="' + r.pageUrl + '" target="_blank">' + r.name + '</a></div>';

            },

            liveType: function(v, r) {
                return Channel.Config.LIVE_TYPE[r.liveType];

            },

            universalCode: function(v, r) {
                if (r.liveType == 1)
                    return '<a href="http://www.tvmao.com/api/EpgDataServlet?secret=Gee6S5dQ&c=' + r.universalCode + '" target="_blank">' + r.universalCode + '</a>';
                else
                    return '';
            },

            defaultLogoUrl: function(v, r) {
                if (r.defaultLogoUrl == undefined)
                    return '生产中...';
                else
                    return '<a target="_blank" href="' + r.defaultLogoUrl + '"><img height="25px" width="60px" src="' + r.defaultLogoUrl + '"></a>';
            },

            maxPlaybackPeriod: function(v, r) {
              return Number(v / 3600).toFixed(2) * 100 / 100 + '小时';
            },

            channelType: function(v, r) {

                return Channel.Config.CHANNEL_TYPE[r.type];
            },

            operate: function(v, r) {
                var htmls = [];
                var name = r.name;

                htmls.push('<div class="oper">');

                if (r.isEnable === -1) {
                    htmls.push('<a class="disabled">预览</a>');
                    htmls.push('<a class="disabled">编目</a>');
                    htmls.push('<a class="disabled">节目单</a>');
                    htmls.push('<a class="disabled">直播流管理</a>');
                    htmls.push('</br>');
                    htmls.push('<a class="disabled">播控中心</a>');
                    //htmls.push('<a class="disabled">预约计划</a>');
                    htmls.push('<a class="disabled">删除</a>');
                    htmls.push('</div>');
                    return htmls.join('');
                }


                if (r.menuShow != undefined) {

                    var program = '',
                        stream = 'disabled',
                        broadcast = 'disabled',
                        reserve = 'disabled';

                    var json = JSON.parse(r.menuShow);


                    if (json.program > 0) {
                        stream = '';
                        if (json.stream > 0) {
                            broadcast = '';
                            if (json.control > 0) {
                                reserve = '';
                            }
                        }
                    }

                }

                if (broadcast == '') {

                    if (!r.alternatePlayCollection)
                        r.alternatePlayCollection = '';

                    htmls.push('<a href="javascript:;" data-id="' + r.id + '" data-type="' + r.liveType + '" data-alternatePlayCollection=\'' + r.alternatePlayCollection + '\' data-qipu-id="' + r.qipuId + '" onclick="Channel.Util.preview(this);">预览</a>');
                } else
                    htmls.push('<a href="javascript:;" class="disabled" data-id="' + r.id + '">预览</a>');
                htmls.push('<a href="./channel_edit.html?id=' + r.id + '" target="_blank">编目</a>');

                var delDisabled = '';

                if (r.liveType == 3) {
                    htmls.push('<a href="./carousel_edit.html?fatherId=' + r.id + '" class="' + program + '" target="_blank">节目单</a>');
                } else
                    htmls.push('<a href="./program_list.html?fatherId=' + r.id + '" class="' + program + '" target="_blank">节目单</a>');


                htmls.push('<a href="./live_stream.html?qipuId='+ r.qipuId+'&id=' + r.id + '&name=' +  encodeURIComponent(name.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">")) + '&livetype=' + r.liveType + '&universalcode=' + r.universalCode.toLowerCase() + '" class="' + stream + '" target="_blank">直播流管理</a>');
                htmls.push('</br><a href="./broadcast_manager.html?id=' + r.id + '&name=' + name + '" class="' + broadcast + '" target="_blank">播控中心</a>');
                //htmls.push('<a href="./reservation_list.html?id=' + r.id + '&name=' + name + '" class="' + reserve + '" target="_blank">预约计划</a>');
                //htmls.push('<a href="javascript:;" >禁用</a>');

                if (r.liveType != 3 || auth.dev())
                    htmls.push('<a href="javascript:;" onclick="Channel.Util.deleteChannel(' + r.id + ');" >删除</a>');
                //htmls.push('<a href="javascript:;" >预览直播流</a>');

                htmls.push('</div>');
                return htmls.join('');
            },

            isEnable: function(v, r) {
                if (r.isEnable === 1) {
                    return '启用';
                } else if (r.isEnable === -1) {
                    return '已删除';
                } else {
                    return '未启用';
                }
            },

            isMemeberFree: function(v, r) {
                if (r.isMemeberFree) {
                    return '免费';
                } else {
                    return '收费';
                }
            },

            status: function(v, r) {

                switch (r.status) {
                    case 'PAIED_AVAILABLE':
                        return '付费已划价';
                        break;

                    case 'PAIED_NOT_AVAILABLE':
                        return '付费未划价';
                        break;

                    case 'FREE':
                        return '免费';
                        break;

                }
            },


            operator: function(v, r) {
                return '<a href="javascript:;" data-id="' + r.id + '" onclick="Channel.Util.operateHistory(this);">详细</a>';
            },
            log_type:function(v, r ){
                return Channel.Config.LOG_TYPE[r.type];
            }
        },

        // 绑定时间控件
        bindDatetimepicker: function(obj) {

            try {
                for (var i in obj) {
                    $(obj[i]).datetimepicker({
                        onClose: function(selectedDate) {
                            $(obj[i]).find('input[name="startDate"]').datepicker("option", "minDate", selectedDate);
                        }

                    });
                }
            } catch (e) {}

        },



        _initEditEvent: function() {
            var self = this;

            // 分类对话框
            $("#category-a").click(function() {
                if ($('input[name="formal"]:checked').val() == 1) {
                    self.showCategoriesDlg();
                    self._showHasSelectedCat();
                }
            });

            $(".channel-edit-form").on("input propertychange", "[name='carousel_table_no']",
                function() {
                    Channel.Dao.carouselTableNo({
                        carousel_table_no: $(this).val(),
                        type: $(".channel-edit-form").find("select[name=type]").val(),
                        channelId: Ancestor.Util.getUrlId('id')
                    }, function(json) {

                        if (json.code == 'A00000') {

                            $("#ctn-tps").text(json.msg).show();

                        } else {
                            $("#ctn-tps").text("").hide();

                        }
                    });
                });



            $("#categories-dlg").on('dblclick', '.parent_category', function() {

                if ($(this).val() > 0) {
                    var title = $(".parent_category").find("option:selected").text();
                    var id = $(".parent_category").val() + '_0';

                    var tmp = $("#category-val>span");

                    var seq = null;
                    $.each($(tmp), function() {

                        if ($(this).attr('data-tag-id') == id)
                            seq = true;

                    });

                    var tag_span = $('<span data-tag-id="' + id + '" class="ui-suggest-value tagmanagerTag" data-tag-label="' + title + '">' + title + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>');

                    if (!seq)
                        $("#category-val").append(tag_span);

                }

            });

            // 大小分类事件绑定
            $("#categories-dlg").on('change', '.parent_category', function() {

                var pcObj = $(this);
                var parent_cate_id = $(this).val()[0];

                var sub_cate = $('.sub_category');
                var options = '';
                if (parent_cate_id > 0) {

                    var request = self.genCategoriesRequestStr(parent_cate_id);

                    Channel.Dao.getCategories({
                        request: request
                    }, function(json) {

                        sub_cate.empty();
                        $.each(json, function(i, item) {
                            options += '<option value="' + item.id + '">' + item.name + '</option>';
                        });
                        sub_cate.html(options);

                        sub_cate.unbind("dblclick").bind("dblclick", function() {
                            var tmp = $("#category-val>span");

                            if ($(this).val() > 0) {
                                var title = $(".parent_category").find("option:selected").text() + '_' + $(this).find("option:selected").text();
                                var id = $(".parent_category").val() + '_' + $(this).val();
                            } else {
                                var title = $(".parent_category option:selected").text();
                                var id = $(".parent_category").val() + '_' +0;
                            }

                            var seq = null;
                            $.each($(tmp), function() {

                                if ($(this).attr('data-tag-id') == id)
                                    seq = true;

                            });

                            var tag_span = $('<span data-tag-id="' + id + '" class="ui-suggest-value tagmanagerTag" data-tag-label="' + title + '">' + title + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>');

                            if (!seq)
                                $("#category-val").append(tag_span);

                        });

                    });

                }
            });


            $('input[name=maxPlaybackPeriod]').blur(function() {
                var val = $(this).val();

                if(isNaN(val)) {
                    $('#mpp-tps').text('最大回看时间必须为数字').show();
                    return;
                }else{
                    $('#mpp-tps').text('').hide();
                }

                var channelId = self._getChannelId("id");

                if(channelId == null) {
                    return;
                }

                Channel.Dao.getProgramMaxDuration({fatherId: channelId}, function (json) {
                    if (json.code == 'undefined' || json.code != 'A00000') {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = '获取节目信息失败';

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });
                    } else {
                        if (json.data !== "") {
                            var programInfo = json.data;
                            programInfo = programInfo.replace(/'/gm, "\"");
                            programInfo = JSON.parse(programInfo);
                            if (programInfo.duration > val*3600) {
                                $('#mpp-tps').text('最大回看时间需要大于等于' + self.formatter.maxPlaybackPeriod(programInfo.duration, null)).show();
                            }else{
                                $('#mpp-tps').text('').hide();
                            }
                        }else{
                            $('#mpp-tps').text('').hide();
                        }
                    }
                });
            });


        },
        _getChannelId: function(id) {
            return this.getUrlId(id);
        },

        _initLiveChannelType: function($container) {
            var self = this;

            // 频道类型
            Channel.Dao.getType({
                type: 'LiveChannelType'
            }, function(json) {
                if (json.code == 'A00000') {
                    Channel.Config.NormalChannel = {},
                    Channel.Config.TempChannel = {};
                    Channel.Config.Carousel = {};
                    $.each(json.data, function(i, n) {
                        if (n.val.indexOf("临时") == -1) {
                            if (n.val.indexOf("爱奇艺") == -1 && n.val != '台湾台')
                                Channel.Config.NormalChannel[n.key] = n.val;
                            else
                                Channel.Config.Carousel[n.key] = n.val;
                        } else
                            Channel.Config.TempChannel[n.key] = n.val;
                    });

                    var html = '';
                    $.each(Channel.Config.NormalChannel, function(i, n) {
                        html += '<option value="' + i + '">' + n + '</option>';
                    });

                    $container.find('select[name="type"]').html(html);
                    self._initInterruptType($container);

                } else {
                    var msg = Stream.Config.REQUEST_FAIL;
                    if (json.msg != undefined)
                        msg = json.msg;

                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                }
            });


        },


        _initLiveType: function($container) {
            var self = this;
            // 直播类型
            Channel.Dao.getType({
                type: 'LiveType'
            }, function(json) {
                if (json.code == 'A00000') {


                    var html = '';
                    $.each(json.data, function(i, n) {
                        html += '<option value="' + n.key + '">' + n.descr + '</option>';
                    });

                    $container.find('select[name="liveType"]').html(html);

                    self._initLiveChannelType($container);

                } else {
                    var msg = Channel.Config.REQUEST_FAIL;
                    if (json.msg != undefined)
                        msg = json.msg;

                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                }

            });


        },

        _initAutomation: function($container, index) {
            var self = this;
            var html = '<option value="">请选择</option>';
            var data = Channel.Config.AUTOMATION_TYPE;
            $.each(data, function(i) {
                html += '<option value="' + i + '">' + data[i] + '</option>';
            });

            $container.find('select[name="automation"]').html(html);
        },

        _initUserCount: function($container, index) {
            var self = this;
            var html =  '';
            var data = Channel.Config.USER_COUNT;
            $.each(data, function(i) {
                html += '<option value="' + i + '">' + data[i] + '</option>';
            });
            $container.find('select[name="userCount"]').html(html);
        },


        _initInterruptType: function($container) {

            var self = this;
            // 播放器提示信息
            Channel.Dao.getType({
                type: 'InterruptType'
            }, function(json) {
                if (json.code == 'A00000') {
                    var html = '';
                    $.each(json.data, function(i, n) {
                        html += '<option value="' + n.key + '">' + n.descr + '</option>';
                    });
                    $container.find('select[name="interruptHintType"]').html(html);
                    self._initChannelData($container)
                } else {
                    var msg = Stream.Config.REQUEST_FAIL;
                    if (json.msg != undefined)
                        msg = '播放器提示信息获取失败';
                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                }

            });

        },

        _writeCarouselTableNoHtml: function(value) {
            var self = this;
            self.carouselTableNoVal = value;
            auth.getAuthData({
                tips: 1,
                url: '/epg/carousel_table_no.html'
            }, function(rt) {

                if (!rt) {
                    $("#carouselTableNo").html('<label class="control-label" for="">轮播台台号<span class="form-must">*</span>：</label>' + '<div class="controls">' + '  <input type="text" name="carousel_table_no" value="' + self.carouselTableNoVal + '" placeholder="台号为整数类型" />' + '<span id="ctn-tps" style="color:red"></span>' + '</div>').show(); // 轮播台台号显示
                }
            });
        },

        _initChannelData: function($container) {

            var self = this;

            // 隐藏收费起止时间
            $('#isMemeberFree').hide();

            // 隐藏压流延时
            $("#sDelay").hide();

            $("#isTest").hide();

            //隐藏专题页url
            $("#subjectUrlGroup").hide();

            //隐藏节目单类型选择
            $("#automationBlock").hide();

            //隐藏节目单类型选择
            $("#automationBlock").hide();

            // 修改时加入id
            var id = this._getChannelId('id');

            if (id != null) {
                $container.append('<input type="hidden" name="id" value="">');

                // 检测是否存在流（限制压流延时是否可修改）
                Stream.Dao.getStreamInfo({
                    'fatherId': id
                }, function(json) {
                    if (json.code == 'undefined' || json.code != 'A00000') {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = '获取频道流信息失败';

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });
                    } else {
                        var hasFLVorHCDN = false;
                        if (json.data.length != 0) {
                            $('#sDelay').find('[name="sliceDelay"]').attr('disabled', 'disabled');
                            //TODO 添加压流延时禁止修改提示
                            //$('#sDelayTip').html('');
                        }

                        $.each(json.data, function() {
                            if (this.formatType === "FLV" || this.formatType === "HCDN" || this.formatType === 'HLFLV') {
                                hasFLVorHCDN = true;
                            }
                        });

                        if(hasFLVorHCDN) {
                            $('#userCountBlock').find('[name="userCount"]').attr('disabled', 'disabled');
                        }
                    }
                });

                Channel.Dao.getSingleChannelData({
                    'id': id
                }, function(json) {

                    if (json.code == 'undefined' || json.code != 'A00000') {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = '初始化频道修改数据失败';

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });
                    } else {

                        // 初始化频道数据
                        var $form = $container;

                        var $elements = $.makeArray($form.prop('elements')).filter(function() {
                            return true; //this.name;
                        });

                        // 保存压流延时原始值
                        Channel.Config.SLICE_DELAY_CHECK.oldValue = json.data.sliceDelay;

                        var name;
                        var key;
                        var hasInit = {};


                        $.each($elements, function() {
                            name = this.name;

                            var value = json.data[name];

                            var liveType = 0;

                            if (this.type == "radio") {

                                if (!hasInit[name]) {
                                    $.each($('input[name="' + this.name + '"]'), function() {

                                        if ($(this).val() == value) {
                                            $(this).prop("checked", true);
                                        } else {
                                            $(this).prop("checked", false);
                                        }
                                    });

                                    hasInit[name] = 1;
                                }

                            } else {

                                if (this.name == 'tag') {

                                    var ids = [];
                                    var tags = json.data[name].split(',');

                                    for (var i = 0; i < tags.length; i++) {
                                        ids.push(tags[i]);
                                    }


                                    self.getParentCategories(ids, function(data) {

                                        self.getSubCategories(data, function() {
                                            $('.tagshow').text(self.subCategories.join(','));

                                        });
                                    });



                                    if (value == 2) {
                                        $("#sDelay").show();
                                        $("#isTest").show();
                                    }

                                }

                                if (this.name == 'logoUrl') {
                                    self.imageObjectEcho($form, value);
                                    //$('.cropimg').html('<img src="' + value + '">');
                                }

                                if (this.name == 'maxPlaybackPeriod') {
                                    value = Number(value / 3600).toFixed(2) * 100 / 100;
                                }


                                $(this).val(value);

                                if (this.name == 'automation') {
                                    $('[name="automation"]').attr('disabled', 'disabled');
                                }

                                if (this.name == 'liveType') {

                                    $('[name=liveType]').attr('disabled', 'disabled');

                                  //  $('#ucode').val('');

                                    if (value == 2 || value == 3) {
                                        $('#ucode').hide();
                                        $('#ucode').find('[name="universalCode"]').attr('disabled', 'disabled');
                                        $('select[name="liveType"]').change();
                                        if (value == 3) {
                                            Channel.Util._writeCarouselTableNoHtml(json.data["carouselTableNo"]);
                                            Stream.Config.ctn = json.data["carouselTableNo"];
                                        }
                                    }

                                    if (value != 3) {
                                        $("#alternatePlayCollectionIdsGroup").hide();
                                    }else{
                                        $("#automationBlock").show();
                                    }

                                    if (value == 2) {
                                        $("#sDelay").show();
                                        $("#isTest").show();
                                    }
                                    liveType = value;
                                }
                                if (this.name == 'description') {
                                    //描述字数限制
                                    Ancestor.Util.limitWordCount($('.channel-edit-form textarea[name="description"]'), 300);
                                }


                                if (this.name == 'alternatePlayCollection' && value) {
                                    var v = JSON.parse(value);

                                    for (var i in v) {

                                        Ancestor.Util.alternatePlayCollectionAppend(v[i]);

                                    }
                                }

                                if(this.name == 'type' && (value == 5 || value == 11)) {
                                    $('[name=type]').attr('disabled', 'disabled');
                                }

                            }

                        });

                        if (json.data["formal"] == 0 && json.data["liveType"] == 2) {
                            $('#category-warn').css("display", "inline-block");
                        }
                    }


                });

            }else{
                $("select[name=liveType]").change();
            }

        },

        // 根据分类id或取对应中文
        getSubCategories: function(ids, callback) {

            var self = this;

            if (ids == '') {
                callback.call(this);
                return;

            }

            var pop_id = ids.shift();

            var _id = pop_id.split('_');

            var pName = '',
                sName = '';

            var request = this.genCategoriesRequestStr(_id[0]);

            Channel.Dao.getCategories({
                request: request
            }, function(json) {

                for (var i = 0; i < Channel.Config.PCAT.length; i++) {
                    if (Channel.Config.PCAT[i].id == _id[0]) {
                        pName = Channel.Config.PCAT[i].name;
                        break;
                    }
                }

                for (var i = 0; i < json.length; i++) {
                    if (json[i].id == _id[1]) {
                        sName = json[i].name;
                        break;
                    }
                }

                if (!sName)
                    self.subCategories.push(pName);
                else
                    self.subCategories.push(pName + '_' + sName);

                self.getSubCategories(ids, callback);

            });


        },


        // 初始化编辑数据修改
        _initEditData: function($container) {
            this._initAutomation($container);
            this._initUserCount($container);
            this._initLiveType($container);
        },

        // 显示已选分类
        _showHasSelectedCat: function() {

            var tags = $('.tagshow').text().split(',');
            var ids = $('input[name="tag"]').val().split(',');
            var tag_span = '';

            if (tags == '') return;

            $.each(tags, function(i, item) {

                tag_span = tag_span + '<span data-tag-id="' + ids[i] + '" class="ui-suggest-value tagmanagerTag" data-tag-label="' + item + '">' + item + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>';

            });

            $("#category-val").append(tag_span);

        },



        checkAutomationType: function(automation){
            return !(automation !== '1' && automation !== '0' && automation !== '2');
        },

        numMulti: function (n1, n2) {
            var baseNum = 0;
            try {
                baseNum += n1.toString().split(".")[1].length;
            } catch (e) {
            }
            try {
                baseNum += n2.toString().split(".")[1].length;
            } catch (e) {
            }
            return Number(n1.toString().replace(".", "")) * Number(n2.toString().replace(".", "")) / Math.pow(10, baseNum);
        },

        checkSubjectUrl: function (data) {
            if (data.hasOwnProperty('subjectUrl') && data.subjectUrl !== '') {
                return data.subjectUrl.split('://')[0] === 'http';
            }
            return true;
        },

        checkAPC: function() {
            var self=this;
            var data = Channel.Config.SLICE_DELAY_CHECK.data;
            // 校验备播库奇谱ID
            if ($("#alternatePlayCollectionIdsGroup").is(":visible") && self._getChannelId('id') != null) {
                self.callApcAPI(data);

            } else {
                self.apcFinalOperation(data);
            }

        },

        checkSliceDelay: function() {
            var self=this;
            var data = Channel.Config.SLICE_DELAY_CHECK.data;
            var newValue = data.sliceDelay;
            var oldValue = Channel.Config.SLICE_DELAY_CHECK.oldValue + '';

            if(!self._getChannelId('id')){
                Channel.Config.SLICE_DELAY_CHECK.headUrl = './channel.html';
                self.checkAPC();
                return;
            }

            if(oldValue && newValue !== oldValue){
                SystemDialog.queryConfirm(Channel.Config.SLICE_DELAY_CHECK.msg, function(flag){
                    if(flag){
                        Channel.Config.SLICE_DELAY_CHECK.headUrl =  './program_list.html?fatherId=' + Channel.Util._getChannelId('id');
                        self.checkAPC();
                    }else{
                        var submit = $.find('#Submit')[0];
                        submit.disabled = '';
                        $(document).tips({
                            content: "频道信息未保存",
                            type: "error"
                        });
                    }
                });
            }else{
                Channel.Config.SLICE_DELAY_CHECK.headUrl = './channel.html';
                self.checkAPC();
            }
        },

        checkMaxPlaybackPeriod: function(data) {
            if (data.hasOwnProperty('maxPlaybackPeriod')) {
                var a = data.maxPlaybackPeriod;
                // 最大回看时间 2*24
                if (a > 48) {
                    return false;
                }
            }
            return true;
        },

        checkMaxPlayBackPeriodWithProgramMaxDuration: function (data, id) {
            var self = this;
            Channel.Dao.getProgramMaxDuration({fatherId: id}, function (json) {
                if (json.code == 'undefined' || json.code != 'A00000') {
                    var msg = Stream.Config.REQUEST_FAIL;
                    if (json.msg != undefined)
                        msg = '获取节目信息失败';

                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                } else {
                    if (json.data !== "") {
                        var programInfo = json.data;
                        programInfo = programInfo.replace(/'/gm, "\"");
                        programInfo = JSON.parse(programInfo);
                        if (programInfo.duration > data.maxPlaybackPeriod) {
                            var msg = "存在节目[" + programInfo.name + "] 时长[" + self.formatter.maxPlaybackPeriod(programInfo.duration, null) + "]大于填写的最大回看时长，请重新填写!";
                            $(document).tips({
                                content: msg,
                                type: "error"
                            });

                            var submit = $.find('#Submit')[0];
                            submit.disabled = '';

                            return;
                        }
                    }

                    Channel.Dao.setChannelModifyData(data, self.onSave); // 修改
                }
            });
        },

        apcFinalOperation: function(data) {
            var self = this;

            // transfer maxPlaybackPeriod to seconds
            if (data.hasOwnProperty('maxPlaybackPeriod')) {
                var a = data.maxPlaybackPeriod;
                a = self.numMulti(a, 3600);
                data.maxPlaybackPeriod = a;
            }

            var id = self._getChannelId('id');
            if (id == null) {
                Channel.Dao.setChannelAddData(data, self.onSave); // 新增
            }else{
                self.checkMaxPlayBackPeriodWithProgramMaxDuration(data, id);
                //Channel.Dao.setChannelModifyData(data, self.onSave); // 修改
            }
        },

        apcErrorOperation: function() {
            var self = this;
            var submit = $.find('#Submit')[0];
            submit.disabled = '';

            $(document).tips({
                content: "备播库节目信息保存出错, 请稍候重试！",
                type: "error"
            });
        },

        apcAdd: function(data, formData) {
            var self = this;
            var request = {};
            var addList = data[0];

            if (addList.length == 0) {
                self.apcFinalOperation(formData);
                return;
            }

            request.url = Channel.Config.APC_CONFIG.apc_add;
            request.type = 'get';
            request.params = {
                channelids: Ancestor.Util.getUrlId('id'),
                qiPuIds: addList.join(',')
            };
            request = JSON.stringify(request);

            Channel.Dao.alternateOperation({
                request: request
            }, function(json) {
                if (typeof(json) == "undefined") {
                    console.log("调用备播库接口失败!");
                    self.apcErrorOperation();

                } else if (json.error_code == '0') {
                    console.log('调用成功' + json);

                    self.apcFinalOperation(formData);
                } else {
                    console.log("获取备播库信息错误!");
                    self.apcErrorOperation();
                }

            });
        },

        apcDelete: function(data, formData) {
            var self = this;
            var request = {};
            var deleteList = data[1];

            if (deleteList.length == 0) {

                setTimeout(function() {
                    self.apcAdd(data, formData);
                }, 3000);

                return;
            }

            request.url = Channel.Config.APC_CONFIG.apc_delete;
            request.type = 'get';
            request.params = {
                channelids: Ancestor.Util.getUrlId('id'),
                qiPuIds: deleteList.join(',')
            };
            request = JSON.stringify(request);

            Channel.Dao.alternateOperation({
                request: request
            }, function(json) {
                if (typeof(json) == "undefined") {
                    console.log("调用备播库接口失败!");
                    self.apcErrorOperation();
                } else if (json.error_code == '0') {
                    console.log('调用成功' + json);

                    setTimeout(function() {
                        self.apcAdd(data, formData);
                    }, 3000);

                } else {
                    console.log("获取备播库信息错误!");
                    self.apcErrorOperation();
                }

            });
        },

        callApcAPI: function(formData) {
            var self = this;
            var request = {};

            request.url = Channel.Config.APC_CONFIG.apc_info;
            request.type = 'get';
            request.params = {
                channelid: Ancestor.Util.getUrlId('id')
            };
            request = JSON.stringify(request);

            //  var beforeApcOperation = this.beforeApcOperation;

            Channel.Dao.alternateOperation({
                request: request
            }, function(json) {
                if (typeof(json) == "undefined") {
                    console.log("调用备播库接口失败!");
                    self.apcErrorOperation();

                } else if (json.error_code == '0') {
                    var qipuIdsNew = [];
                    var qipuIdsInfo = [];
                    var addList = [];
                    var deleteList = [];

                    if ($('input[name="alternatePlayCollection"]').val() != '') {

                        var tempData = JSON.parse($('input[name="alternatePlayCollection"]').val());
                        $.each(tempData, function(key, value) {
                            var qipuId = value.qipuId;
                            qipuIdsNew.push(qipuId);
                        });
                    }

                    if (json.info != "") {
                        info = json.info.replace('\{', '').replace('\}', '').split(',');
                        $.each(info, function(key, value) {
                            qipuIdsInfo.push(Number(value));
                        });
                    }
                    var tempList = $.unique($.merge($.merge([], qipuIdsNew), qipuIdsInfo));

                    $.each(tempList, function(key, val) {
                        if ($.inArray(val, qipuIdsNew) < 0) {
                            deleteList.push(val);
                        }

                        if ($.inArray(val, qipuIdsInfo) < 0) {
                            addList.push(val);
                        }
                    });

                    self.apcDelete([addList, deleteList], formData);
                } else {
                    console.log("获取备播库信息错误!");
                    self.apcErrorOperation();

                }

            });

        },

        save: function(data) {

        },
        onSave: function(json) {
            if (json.code == 'A00000') {
                var url = Channel.Config.SLICE_DELAY_CHECK.headUrl;

                setTimeout(function() {
                    window.location.href = url;
                }, 2000);

                var html = '操作成功，系统将在两秒后跳转到节目页面,<a href="' + url + '" target="_self">立即跳转</a>';
                $(document).tips({
                    content: html,
                    type: "loading"
                });
            } else {

                $('#Submit').removeAttr("disabled");

                var msg = Stream.Config.REQUEST_FAIL;
                if (json.msg != undefined)
                    msg = json.msg;

                $(document).tips({
                    content: msg,
                    type: "error"
                });
            }

        },

        genCategoriesRequestStr: function(father_id) {
            var request = {};
            request.url = 'http://xinqi.if.iqiyi.com/basic/categories.json';
            request.type = 'get';
            request.params = {
                father_id: father_id
            };

            return JSON.stringify(request);
        },

        showCategoriesDlg: function() {

            var $container = $("#categories-dlg");

            $container.dialog({
                title: '对应列表分类',
                appendTo: null,
                modal: true,
                width: 450,
                //  height:380,
                //      maxHeight: 380,
                position: ['top', 'top+20'],
                buttons: [{
                    text: '确定', //  提交分类
                    click: function() {

                        var tags = [],
                            ids = [];


                        $.each($("#category-val").find('span'), function() {

                            ids.push($(this).attr("data-tag-id"));
                            tags.push($(this).attr("data-tag-label"));
                        });
                        //console.log(ids);
                        //console.log(tags);
                        var tags = $('.tagshow').text(tags.join(','));
                        var ids = $('input[name="tag"]').val(ids.join(','));

                        $(this).dialog('close');
                    }
                }, {
                    text: '取消',
                    click: function() {
                        $(this).dialog('close');
                    }
                }],

                open: function() {
                    $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');

                },
                close: function() {

                }

            });

            var $tmpl = $("#categories");

            this.getParentCategories('', function() {
                $container.html($tmpl.tmpl({
                    parentCategory: Channel.Config.PCAT
                }));
            });


        },


        // 获取大分类
        getParentCategories: function(data, callback) {
            var request = this.genCategoriesRequestStr(0);

            if (!Channel.Config.PCAT) {
                Channel.Dao.getCategories({
                    request: request
                }, function(json) {

                    Channel.Config.PCAT = json;

                    callback.call(this, data);

                });
            } else {
                callback.call(this, data);
            }

        },

        // 子分类
        subCategories: [],



        getValidator: function($container, config) {
            // var $container = this.$container;
            var $form = $container;
            var validator = Validator.getValidator($form, config);

            return validator;
        },

        setContainer: function($container) {
            this.$container = $container;
        },

        bindChannelEvent: function() {
            var self = this;
        },

        // 历史记录
        operateHistory: function(obj) {
            var self = this;
            var id = $(obj).attr('data-id');
            auth.getAuthData({
                tips: 1,
                url: '/epg/channel_log.html'
            }, function(rt) {
                if (!rt) {
                    Channel.Config.AUTH_CHECK.technologist = true
                }
                var tableConfig = $.extend(true, {}, Channel.Config.TABLE_LOG );
                tableConfig.width = Channel.Config.AUTH_CHECK.technologist ? 875 : 425
                var colModel = tableConfig.colModel;
                var newColModel = [];
                var colModelConfig = Channel.Config.TABLE_COLMODEL_CONFIG;

                $.each(colModel, function(i, model) {
                    newColModel.push(colModelConfig[model]);
                });
                tableConfig.colModel = newColModel;
                tableConfig.colModel[4].hidden = !Channel.Config.AUTH_CHECK.technologist;
                $('#logList').jqGrid(tableConfig);
                self.openDlg($("#o-h-dlg"), '历史记录',Channel.Config.AUTH_CHECK.technologist ? 900 : 450 , 600);
                $('#logList').jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: {id:id}
                }).trigger('reloadGrid');
            });
        },


        // 预览
        preview: function(obj) {
            var self = this,
                id = $(obj).attr('data-id'),
                type = $(obj).attr('data-type'),
                qipuId = $(obj).attr('data-qipu-id'),
                alternatePlayCollection = $(obj).attr('data-alternatePlayCollection'),
                $container = $('#preview');

            if (alternatePlayCollection) {
                alternatePlayCollection = JSON.parse(alternatePlayCollection);
            }

            Channel.Config.programTypeData = Channel.Config.programTypeData || {};

            if ($.isEmptyObject(Channel.Config.programTypeData)) {
                Channel.Dao.getType({
                    type: 'ContentType'
                }, function(json) {
                    if (json.code == 'A00000') {

                        $.each(json.data, function(index, element) {
                            Channel.Config.programTypeData[element.key] = element.descr;
                        });

                        if (type == 3) {
                            self._program(type, id, qipuId, alternatePlayCollection, self, $container);
                            // self._carousel(id,qipuId,alternatePlayCollection, self, $container);
                        } else {
                            self._program(type, id, qipuId, alternatePlayCollection, self, $container);
                        }

                    } else {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = json.msg;

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });
                    }

                });

            } else {
                if (type == 3) {
                    this._program(type, id, qipuId, alternatePlayCollection, self, $container);
                    //this._carousel(id,qipuId,alternatePlayCollection, self, $container);
                } else {
                    this._program(type, id, qipuId, alternatePlayCollection, self, $container);
                }
            }

        },


        _flvPlayer: function(src) {
            return '<embed width="640" height="420"' +
                ' src="http://www.iqiyi.com/common/flashplayer/20141218/LivePlayer_3_0_3_4.swf" ' +
                'quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
                ' align="middle"' +
                ' play="true"' +
                ' loop="true"' +
                ' scale="showall"' +
                ' wmode="window"' +
                ' devicefont="false"' +
                ' bgcolor="#000000"' +
                ' name="player"' +
                ' menu="true"' +
                ' allowfullscreen="true"' +
                ' allowscriptaccess="always"' +
                ' flashvars="vid=' + src + '&source=live.lego.iqiyi.com&cid=qc_100001_300089"' +
                ' salign="" ' +
                'type="application/x-shockwave-flash">';

        },

        _mp4Player: function(src) {
            return '<video width=362 height=200' +
                ' id="MobileVideo" ' +
                'autoplay="autoplay"' +
                ' src="' + src + '" ' +
                'controls="controls">' +
                '您的浏览器不支持 video 标签'+
            '</video>';
        },

        // 预览节目列表
        _program: function(cType, id, qipuId, alternatePlayCollection, obj, $container) {
            var self = this;
            var currentDateArr = Com.date.getCurrentDate().split('/'),
                currentDateStr = '',
                currentDate = '';

            if (currentDateArr.length > 3) {
                currentDateArr[0] = currentDateArr[1];
                currentDateArr[1] = currentDateArr[2];
                currentDateArr[2] = currentDateArr[3];
            }

            currentDate = currentDateArr[0] + '-' + currentDateArr[1] + '-' + currentDateArr[2];
            var sendObj = {
                    startDate: currentDate + " 00:00:00",
                    endDate: currentDate + " 23:59:59",
                    fatherId: id,
                    pageSize: 400
                },
                currentDateStr = currentDateArr[0] + '年' + currentDateArr[1] + '月' + currentDateArr[2] + '日';

            // 节目列表
            Channel.Dao.getProgramListByDay(sendObj, function(json) {

                if (json.code == 'A00000') {

                    var list = {
                        am: [],
                        pm: []
                    };

                    $.each(json.data.result, function(index, element) {
                        if (cType != 3) element.live = 2;
                        json.data.result[index]['type'] = Channel.Config.PLAY_TYPE[element.live];

                        if (new Date() >= new Date(json.data.result[index]['startPlayTime']) && new Date() <= new Date(json.data.result[index]['endPlayTime']))
                            json.data.result[index]['playing'] = true;

                        if (new Date(json.data.result[index]['startPlayTime']) < new Date(currentDate + " 12:00:00")) {
                            /*
                            if(json.data.result[index]['playing'])
                                list.am.unshift(json.data.result[index]);
                            else*/
                            list.am.push(json.data.result[index]);
                        } else {
                            /*
                            if(json.data.result[index]['playing'])
                                list.pm.unshift(json.data.result[index]);
                            else*/
                            list.pm.push(json.data.result[index]);
                        }
                    });

                    obj.openDlg($container, '预览', 1180, 820);
                    var $tmpl = $("#operate-preview");


                    $.each(alternatePlayCollection, function(index, element) {

                        alternatePlayCollection[index]['contentType'] = Channel.Config.programTypeData[element.contentType];
                        if (!element.duration)
                            alternatePlayCollection[index]['duration'] = '0时0分0秒';
                        else
                            var theTime = parseInt(element.duration / 1000); // 秒
                        var theTime1 = 0; // 分
                        var theTime2 = 0; // 小时
                        if (theTime > 60) {
                            theTime1 = parseInt(theTime / 60);
                            theTime = parseInt(theTime % 60);
                            if (theTime1 > 60) {
                                theTime2 = parseInt(theTime1 / 60);
                                theTime1 = parseInt(theTime1 % 60);
                            }
                        }
                        var result = "" + parseInt(theTime) + "秒";
                        if (theTime1 > 0) {
                            result = "" + parseInt(theTime1) + "分" + result;
                        }
                        if (theTime2 > 0) {
                            result = "" + parseInt(theTime2) + "小时" + result;
                        }

                        alternatePlayCollection[index]['duration'] = result;

                    });

                    $container.html($tmpl.tmpl({
                        list: list,
                        backup: alternatePlayCollection,
                        date: currentDateStr
                    }));


                    if (new Date() < new Date(currentDate + " 12:00:00")) {
                        $('.nav-tabs a:first').tab('show');
                        self._scrollProgramList($("#am"));
                        self._programListScrollEvent("#am");
                    } else {
                        $('.nav-tabs a:last').tab('show');
                        self._scrollProgramList($("#pm"));
                        self._programListScrollEvent("#pm");
                    }

                    // 获取预览流
                    Channel.Dao.getPreviewStream({
                        qipuId: qipuId
                    }, function(json) {
                        if (json.code == 'A00000') {
                            var flvPlayer = self._flvPlayer(json.data.flv);

                            $("#flv").html(flvPlayer);
                            $("#mp4").html("mp4加载失败!");
                        } else {
                            $("#flv").html("flv加载失败!");
                            $("#mp4").html("mp4加载失败!");
                        }


                    });


                } else {
                    var msg = Stream.Config.REQUEST_FAIL;
                    if (json.msg != undefined)
                        msg = json.msg;

                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                }


            });
        },

        // 滚动滚动条到当前播放位置
        _scrollProgramList: function(obj) {
            var offset = 0,
                top = 0;

            $.each(obj.find("table tr"), function(i, item) {
                var $this = $(item);
                offset += $(item).height();
                if ($this.attr('cur-program') == 'playing') {
                    return false;
                }

            });

            $divObj = obj.find("div");
            var height = $divObj.height();

            if (offset > height) {
                top = offset - height;
            }

            $divObj.scrollTop(top);
        },
        // 节目列表滚动事件
        _programListScrollEvent: function(slc) {
            var self = this;
            $("a[href=" + slc + "]").unbind("click").bind("click", function() {
                $(slc).addClass("active");
                self._scrollProgramList($(slc));
            });
        },
        // 预览备播库列表
        _carousel: function() {},

        // 获取类型写入config
        getType: function(options) {

            Channel.Dao.getType({
                type: options.type
            }, function(json) {

                if (json.code == 'A00000') {

                    var valField = 'val';

                    if (options.type == 'LiveType') {
                        var valField = 'descr';
                    }

                    $.each(json.data, function(i, n) {
                        if (n != undefined)
                            Channel.Config[options.cfgName][n.key] = n[valField];
                    });

                    if (typeof(options.requestLoaded) == 'function') {
                        options.requestLoaded();
                    }

                } else {
                    var msg = Stream.Config.REQUEST_FAIL;
                    if (json.msg != undefined)
                        msg = json.msg;

                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                }
            });

        },

        deleteChannel: function(id) {

            auth.getAuthData({
                tips: 1,
                url: '/epg/channel_delete.html'
            }, function(rt) {

                if (rt) {
                    $(document).tips({
                        content: '很抱歉，您没有删除的权限!',
                        type: "error"
                    });

                    return;
                }

                //if(!window.confirm('你确定要删除吗？'))
                //return;
                SystemDialog.queryConfirm("你确定要删除吗？", function(flag) {
                    if (flag === true) {

                        Channel.Dao.deleteChannelData({
                            id: id
                        }, function(json) {

                            if (json.code == 'A00000') {

                                var sg = Channel.Action.getChannelGrid({});
                                sg.query();

                            } else {

                                var msg = Stream.Config.REQUEST_FAIL;
                                if (json.msg != undefined)
                                    msg = json.msg;

                                $(document).tips({
                                    content: msg,
                                    type: "error"
                                });

                            }


                        });
                    }
                });

            });
        }
    });

});